package arkham.data;

import java.util.*;
import arkham.data.Globals.GateColor;
import arkham.jaxb.encounter.*;
import arkham.util.AHLogger;

public class GateCard implements NamedEntity {
	
	private String name;
	private GateColor gateColor;
	private HashMap<String, EventNode> encounters;
	
	public GateCard(String name)
	{
		this.name = name;
		encounters = new HashMap<String, EventNode>(3);
	}

	/**
	 * Gets the name of the gate card
	 * @return the name
	 */
	public String getName() 
	{
		return name;
	}

	/**
	 * Gets the color of the gate card
	 * @return the gate color
	 */
	public GateColor getGateColor() 
	{
		return gateColor;
	}
	
	public Set<String> getLocationSet()
	{
		return encounters.keySet();
	}
	
	/**
	 * Checks if this gate card has a specific encounter for a particular 
	 * other world location
	 * @param location The location to check
	 * @return true if it does, false otherwise
	 */
	public boolean hasSpecificEncounter(String location)
	{
		return encounters.containsKey(location);
	}
	
	/**
	 * Get the encounter on the gate card corresponding to a location.
	 * @param location The location to check
	 * @return the encounter of the encounter. Will return the "Other" 
	 * encounter if it not one of the location-specific encounters
	 */
	public EventNode getOtherWorldEncounter(String location)
	{
		if (encounters.containsKey(location))
		{
			return encounters.get(location);
		}
		else
		{
			return encounters.get("Other");
		}
	}
	
	@Override
	public String toString()
	{
		return name;
	}
	
	/**
	 * Creates the data representation of the gate card from the XML info
	 * and performs a stringent validation check to make sure the XML data is
	 * valid. 
	 * <br>Will return <b>null</b> on a failure.
	 * 
	 * @param xmlgatecard the XML gate card info
	 * @return the data representation of the gate card
	 */
	public static GateCard createGateCardFromXml(GateCardType xmlgatecard)
	{
		GateCard gate = new GateCard(xmlgatecard.getName());
		if (!GateColor.isValidGateColor(xmlgatecard.getColor()))
		{
			AHLogger.error("Gate " + gate.toString() + " has invalid gate color: " + 
					xmlgatecard.getColor());
			return null;
		}
		gate.gateColor = GateColor.getGateColor(xmlgatecard.getColor());
		boolean otherFound = false;
		for (EventNode eventnode : xmlgatecard.getOtherworld())
		{
			String location = eventnode.getLocation();
			gate.encounters.put(location, eventnode);
			if (location.equals("Other")) 
			{
				otherFound = true;
			}
		}
		if (!otherFound)
		{
			AHLogger.error("Gate " + gate + " must define an encounter for Other");
			return null;
		}
		return gate;
	}
}
